package org.piaohao.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.FileKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.piaohao.model.Policy;
import org.piaohao.util.file.AntZip;
import org.piaohao.util.file.FileUtil;
import org.piaohao.util.string.JsonUtil;
import org.piaohao.util.string.UUIDGenerator;

/**
 * Created on : 2013-5-4, 17:22:58
 *
 * @author piaohao
 */
public class PolicyController extends Controller {

    public static final String moduleName = "政策展现模块";

    public void index() {
        render("/pages/policy/policy.jsp");
    }

    public void getTree() {
        try {
            String id = getPara("id");
            List<Policy> policys;
            if (id.equals("root")) {
                policys = Policy.dao.find("select * from t_policy where p_id is null");
            } else {
                policys = Policy.dao.find("select * from t_policy where p_id =?", id);
            }
            renderJson(policys);
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    public void init() {
        try {
            Db.update("delete from t_policy");
            new Policy().set("id", "0").set("text", "政策法规").save();
            UploadFile file = getFile("file", PathKit.getWebRootPath() + "/upload", 1024 * 1024 * 100);
            File f = file.getFile();
            String folder = f.getAbsolutePath();
//            String folderName = folder.substring(0, folder.indexOf("."));
            String folderName = folder.substring(0, folder.lastIndexOf("\\"));
            File folderFile = new File(folderName);
//            if(!folderFile.exists()){
//                folderFile.mkdir();
//            }
            AntZip zip = new AntZip();
            zip.unZip(f, folderName);
            if (f.exists()) {
                f.delete();
            }
            processFile(folderFile);
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    private void processFile(File file) {
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                try {
                    for (File tmp : files) {
                        Policy policy = new Policy();
                        String name = tmp.getName();
                        String path = tmp.getAbsolutePath();
                        policy.set("id", UUIDGenerator.getUUID());
                        policy.set("text", name);
                        policy.set("path", path);
                        String pPath = tmp.getParentFile().getAbsolutePath();
                        List<Policy> policys = Policy.dao.find("select * from t_policy where path=?", pPath);
                        if (policys != null && !policys.isEmpty()) {
                            policy.set("p_id", policys.get(0).get("id"));
                        } else {
                            policy.set("p_id", "0");
                        }
                        if (tmp.isDirectory()) {
                            policy.set("leaf", false);
                            policy.save();
                            processFile(tmp);
                        } else {
                            if (name.endsWith(".doc") || name.endsWith(".docx")) {
                                policy.set("icon", "resource/images/ico/word.png");
                            } else if (name.endsWith(".pdf")) {
                                policy.set("icon", "resource/images/ico/pdf.gif");
                            } else if (name.endsWith(".xls")) {
                                policy.set("icon", "resource/images/ico/xls.gif");
                            }
                            policy.set("leaf", true);
                            policy.save();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void view() {
        try {
            String id = getPara("id");
            Policy policy = Policy.dao.findById(id);
            String path = policy.getStr("path");
            Boolean leaf = policy.getBoolean("leaf");
            String swfPath = policy.getStr("swf_path");
            String name = policy.getStr("text");
            String swfName;
            if (swfPath != null && !swfPath.equals("")) {
                swfName = swfPath.substring(swfPath.lastIndexOf("\\") + 1);
                setAttr("swfPath", swfName);
            } else {
                swfName = name.substring(0, name.lastIndexOf(".")) + ".swf";
                swfPath = PathKit.getWebRootPath() + "\\policy_swf\\" + swfName;
                if (path.endsWith(".doc") || path.endsWith(".docx")) {
                    FileUtil.office2swf(path, swfPath);
                } else if (path.endsWith(".pdf")) {
                    FileUtil.convertPDF2SWF(path, swfPath);
                }
                policy.set("swf_path", swfPath);
                policy.update();
                setAttr("swfPath", swfName);
            }

            if (leaf) {
                render("/pages/policy/detail.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add() {
        try {
            UploadFile file = getFile("file", PathKit.getWebRootPath() + "/tmp", 1024 * 1024 * 100);
            File f = file.getFile();
            Policy policy = getModel(Policy.class);

            FileUtil.cutGeneralFile(PathKit.getWebRootPath() + "/tmp/" + f.getName(), policy.getStr("path"));

            Policy p = new Policy();
            String name = f.getName();
            if (name.endsWith(".doc") || name.endsWith(".docx")) {
                p.set("icon", "resource/images/ico/word.png");
            } else if (name.endsWith(".pdf")) {
                p.set("icon", "resource/images/ico/pdf.gif");
            } else if (name.endsWith(".xls")) {
                p.set("icon", "resource/images/ico/xls.gif");
            }
            p.set("upload_time", new Timestamp(new Date().getTime()));
            p.set("org_id", (String) getSessionAttr("orgId"));
            p.set("text", name);
            p.set("id", UUIDGenerator.getUUID()).set("path", policy.getStr("path") + "\\" + f.getName()).
                    set("leaf", true).set("p_id", policy.getStr("p_id")).save();
            Map map = new HashMap();
            map.put("policy", p);
            renderJson(JsonUtil.printSuccess(true, "成功", map));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void delete() {
        try {
            String[] idArr = getParaValues("ids");
            for (int i = 0; i < idArr.length; i++) {
                Policy policy = Policy.dao.findById(idArr[i]);
                String path = policy.getStr("path");
                boolean deleted = Policy.dao.deleteById(idArr[i]);
                if (deleted) {
                    FileKit.delete(new File(path));
                }
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }
}
